using Rogan.Utility;
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Rogan.Utility.Common;

namespace Rogan.Data.SqlServer
{
	public class SqlServerProvider : DbProvider
	{
		public override string RowAutoID
		{
			get
			{
				return "select scope_identity()";
			}
		}
		public override bool SupportBatch
		{
			get
			{
				return true;
			}
		}
		public SqlServerProvider(string connectionString) : this(connectionString, SqlClientFactory.Instance)
		{
		}
		public SqlServerProvider(string connectionString, DbProviderFactory dbFactory) : base(connectionString, dbFactory, '[', ']', '@')
		{
		}
		public override void PrepareCommand(DbCommand cmd)
		{
			base.PrepareCommand(cmd);
			foreach (DbParameter dbParameter in cmd.Parameters)
			{
				if (dbParameter.Direction != ParameterDirection.Output && dbParameter.Direction != ParameterDirection.ReturnValue)
				{
					object value = dbParameter.Value;
					if (value != DBNull.Value)
					{
						Type type = value.GetType();
						SqlParameter sqlParameter = (SqlParameter)dbParameter;
						if (type == typeof(Guid))
						{
							sqlParameter.SqlDbType = SqlDbType.UniqueIdentifier;
						}
						else
						{
							DbType dbType = dbParameter.DbType;
							switch (dbType)
							{
							case DbType.AnsiString:
								if (value.ToString().Length > 8000)
								{
									sqlParameter.SqlDbType = SqlDbType.Text;
								}
								break;
							case DbType.Binary:
								if (((byte[])value).Length > 8000)
								{
									sqlParameter.SqlDbType = SqlDbType.Image;
								}
								break;
							default:
								if (dbType != DbType.DateTime)
								{
									switch (dbType)
									{
									case DbType.Object:
										sqlParameter.SqlDbType = SqlDbType.NText;
										dbParameter.Value = SerializationManager.Serialize(value);
										goto IL_121;
									case DbType.SByte:
									case DbType.Single:
										goto IL_121;
									case DbType.String:
										if (value.ToString().Length > 4000)
										{
											sqlParameter.SqlDbType = SqlDbType.NText;
											goto IL_121;
										}
										goto IL_121;
									case DbType.Time:
										break;
									default:
										goto IL_121;
									}
								}
								sqlParameter.SqlDbType = SqlDbType.DateTime;
								break;
							}
							IL_121:
							if (sqlParameter.SqlDbType == SqlDbType.DateTime && type == typeof(TimeSpan))
							{
								sqlParameter.Value = new DateTime(1900, 1, 1).Add((TimeSpan)value);
							}
						}
					}
				}
			}
		}
	}
}
